/* 
需求
1 发送请求获取数据 渲染页面 

2 新增
  1 给 按钮 绑定点击事件 
    1 显示模态框 
          data-bs-toggle="modal"
          data-bs-target="#模态框id"
    2 显示模态框  
      const myModal = new bootstrap.Modal("#modal", {});
      myModal.show();
  2 给新增模态框中 3个下拉列表 初始化 
    1 先给 省下拉列表做初始化 
    2 给 省 绑定change事件 来渲染 城市数据 
    3 给 城市 绑定 change事件 来渲染 区 数据
  3 给from标签绑定提交事件（补充 如何做到 form外面，button控制form提交）
    1 阻止默认行为
    2 快速获取表单数据
    3 进行合法性校验
    4 调用新增接口
    5 关闭模态框
    6 重置表单
    7 提醒用户
    8 刷新数据 

3 编辑
  1 给编辑按钮绑定点击事件 - 委托
    1 判断当前点击的是不是 编辑
    2 弹出模态框 
    3 获取待编辑的数据的id 
    4 发送请求获取id对应的数据 obj
    5 快速把obj数据设置到对应的表单上
  2 触发提交事件
    1 判断当前是新增还是编辑
    2 新增 - 调用新增接口
    2 编辑 - 调用编辑接口

 */
// 获取dom
const tbody = document.querySelector("tbody.list"); // 表格
const openModal = document.querySelector("#openModal"); // +号按钮
const addform = document.querySelector("#form"); // 模态框表单
const provinceDom = document.querySelector("[name=province]");
const cityDom = document.querySelector("[name=city]");
const areaDom = document.querySelector("[name=area]");
const modalTitle = document.querySelector(".modal-title"); // h5标签
// console.log(tbody);

init();
function init() {
  render();
  // 省份
  province();
  //城市
  provinceDom.addEventListener("change", function (e) {
    city(provinceDom.value);
  });
  // 区县
  cityDom.addEventListener("change", function (e) {
    area(provinceDom.value, cityDom.value);
  });
}
// 渲染页面
async function render() {
  const res = await axios({
    url: "/students",
  });
  // console.log(res);
  // debugger;
  const html = res.data.data.reduce((prev, item) => {
    const {
      id,
      name,
      age,
      gender,
      group,
      hope_salary,
      salary,
      province,
      city,
      area,
    } = item;
    return (
      prev +
      `
    <tr>
    <td>${name}</td>
    <td>${age}</td>
    <td>${gender === 1 ? "女" : "男"}</td>
    <td>${group}</td>
    <td>${hope_salary}</td>
    <td>${salary}</td>
    <td>${province + city + area}</td>
    <td>
      <a href="javascript:;" class="text-success mr-3"><i data-id="${id}" class="bi bi-pen">修改</i></a>
      <a href="javascript:;" class="text-danger"><i data-id="${id}" class="bi bi-trash">删除</i></a>
    </td>
  </tr>
    `
    );
  }, "");
  tbody.innerHTML = html;
}
render();

// 点击+号弹出 模态框
// const addmodal = document.querySelector("#modal")
openModal.addEventListener("click", function (e) {
  $("#modal").modal("show");
  modalTitle.innerText = "添加学员";
});
// 新增
addform.addEventListener("submit", async function (e) {
  e.preventDefault();
  const data = serialize(this, { hash: true, empty: true });
  console.log(data);
  const {
    name,
    gender,
    age,
    group,
    hope_salary,
    salary,
    province,
    city,
    area,
  } = data;
  /* console.log(gender);
  console.log(typeof +age);
  console.log(group); */
  let res;
  if (modalTitle.innerText === "添加学员") {
    res = await axios({
      url: "/students",
      method: "post",
      data: {
        name,
        gender: +gender,
        age: +age,
        group: +group,
        hope_salary: +hope_salary,
        salary: +salary,
        province,
        city,
        area,
      },
    });
  } else {
    res = await axios({
      url: "/students/:id",
      method: "put",
      data: {
        id,
        name,
        gender: +gender,
        age: +age,
        group: +group,
        hope_salary: +hope_salary,
        salary: +salary,
        province,
        city,
        area,
      },
    });
  }
  // 重置表单
  if (res.status == 201) {
    console.log(res);
    addform.reset();
    // console.log(res);
    $("#modal").modal("hide");
    document.querySelector("#myToast .toast-body").innerHTML = res.data.message;
    myToast.show();
    render();
  }
});

// 获取省份
async function province() {
  const res = await axios({
    url: "/api/province",
  });
  // console.log(res);
  provinceDom.innerHTML = res.data.data.reduce((prve, item) => {
    // console.log(item);
    return prve + `<option value="${item}">${item}</option>`;
  }, `<option value="">--省份--</option>`);
}
// 城市
async function city(pname) {
  const res = await axios({
    url: "/api/city",
    params: {
      pname,
    },
  });
  cityDom.innerHTML = res.data.data.reduce((prve, item) => {
    // console.log(item);
    return prve + `<option value="${item}">${item}</option>`;
  }, `<option value="">--城市--</option>`);
  areaDom.innerHTML = `<option value="">--地区--</option>`;
}
// 县区
async function area(pname, cname) {
  const res = await axios({
    url: "/api/area",
    params: {
      pname,
      cname,
    },
  });
  areaDom.innerHTML = res.data.data.reduce((prve, item) => {
    // console.log(item);
    return prve + `<option value="${item}">${item}</option>`;
  }, `<option value="">--地区--</option>`);
}
// 编辑
tbody.addEventListener("click", async function (e) {
  if (e.target.classList.contains("bi-pen")) {
    $("#modal").modal("show");
    // console.log(123);
    id = e.target.dataset.id;
    console.log(id);

    const res = await axios({
      url: `/students/${id}`,
    });
    // console.log(res);
    const data = res.data.data;
    console.log(data);
    await city(data.province);
    await area(data.province, data.city);
    const newlist = addform.querySelectorAll("[name]");
    console.log(newlist);
    newlist.forEach((item) => {
      console.log(item);
      if (item.name !== "gender") {
        addform.querySelector(`[name=${item.name}]`).value = data[item.name];
      }
      addform.querySelector(
        `[name=gender][value='${data.gender}']`
      ).checked = true;
    });
  } else if (e.target.classList.contains("bi-trash")) {
    // console.log(123);
    id = e.target.dataset.id;
    if (confirm("确定删除吗")) {
      const res = await axios({
        url: `/students/${id}`,
        method: "delete",
      });
    }
  }
  render();
});
